﻿using System;
using System.Linq;
using System.Collections;
using System.Data;
using Telerik.Web.UI;
using System.Web.UI;
using KPIS.GERP.GAMS.DAL;
using KPIS.GERP.GAMS.MODEL;
using KPIS.GERP.GAMS.APP.App_UI.Commons;
using System.Collections.Generic;

namespace KPIS.GERP.GAMS.APP.App_UI.Forms
{
    public partial class CloseAccountPeriod : System.Web.UI.Page
    {
        Commons.Main main = new Commons.Main();
        D_ACM_MAS_FISCAL_Period d_acm_fiscal_period = new D_ACM_MAS_FISCAL_Period();
        D_ACM_GENERATE_ACCOUNT_Auto auto = new D_ACM_GENERATE_ACCOUNT_Auto();
        D_ACM_MAS_Account account = new D_ACM_MAS_Account();
        D_ACM_MAS_BaseAccount baseAccount = new D_ACM_MAS_BaseAccount();
        D_BGM_MAS_Source source = new D_BGM_MAS_Source();
        D_ACM_GENERAL_Ledger gl = new D_ACM_GENERAL_Ledger();
        MailMerge mailMerge = new MailMerge();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtBgmYear.Text = source.GetCurrentBgmYear();
            }
        }

        protected void grd1_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
        {
            GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem;
            int nTranSeq = main.ConvertNullInt(main.WebString(dataItem["tran_seq"].Text)) ?? 0;
            e.DetailTableView.DataSource = ((List<M_ACM_GENERAL_Ledger>)ViewState["modelSubs"]).Where(m => m.tran_seq == nTranSeq).ToList();
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            int nEmpSeq = Convert.ToInt32(Session["EmpSeq"]);

            try
            {
                var modelMains = (List<M_ACM_GENERAL_Ledger>)ViewState["modelMains"];
                var modelSubs = (List<M_ACM_GENERAL_Ledger>)ViewState["modelSubs"];

                //INSERT Transaction_group case have new group
                foreach (M_ACM_GENERAL_Ledger modelMain in (List<M_ACM_GENERAL_Ledger>)modelMains)
                {
                    int nOldTranSeq = modelMain.tran_seq;
                    modelMain.created_when = DateTime.Now;

                    string strTranSeq = gl.Insert_Transaction(modelMain, true);

                    if (string.IsNullOrEmpty(strTranSeq))
                    {
                        return;
                    }

                    foreach (M_ACM_GENERAL_Ledger modelSub in modelSubs.Where(m => m.tran_seq == nOldTranSeq).ToList())
                    {
                        modelSub.tran_seq = Convert.ToInt32(strTranSeq);
                        modelSub.created_when = DateTime.Now;

                        gl.Insert_DB_CR(modelSub);
                    }
                }

                ViewState["modelMains2"] = new List<M_ACM_GENERAL_Ledger>();
                ViewState["modelSubs2"] = new List<M_ACM_GENERAL_Ledger>();
                //string strBgmYear = txtBgmYear.Text.Trim();

                //try
                //{
                //    if (strBgmYear.Length == 4)
                //    {
                //        int nBgmYear = Convert.ToInt32(txtBgmYear.Text);
                //        DateTime dtStart = new DateTime(nBgmYear - 544, 10, 1);
                //        DateTime dtEnd = new DateTime(nBgmYear - 543, 9, 30);

                //        // ล้างรายได้ ค่าใช้จ่าย
                //        //IncomeVsOutcome("1", dtStart, dtEnd);
                //        //IncomeVsOutcome("11", dtStart, dtEnd);

                //        // ยอดยกมา
                //        Transfer("1", dtStart, dtEnd);
                //        Transfer("11", dtStart, dtEnd);

                //        grd2.DataSource = ((List<M_ACM_GENERAL_Ledger>)ViewState["modelMains2"]);
                //        grd2.DataBind();
                //    }
                //    else
                //    {
                //        lblError3.Text = "กรุณากรอกปีงบประมาณให้ถูกต้อง";
                //        return;
                //    }

                //    lblError3.Text = "";
                //}
                //catch (Exception ex)
                //{
                //    lblError3.Text = ex.Message;
                //}

                main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

            }
        }

        protected void cmdCalculate_Click(object sender, EventArgs e)
        {
            ViewState["modelMains"] = new List<M_ACM_GENERAL_Ledger>();
            ViewState["modelSubs"] = new List<M_ACM_GENERAL_Ledger>();
            string strBgmYear = txtBgmYear.Text.Trim();

            try
            {
                if (strBgmYear.Length == 4)
                {
                    int nBgmYear = Convert.ToInt32(txtBgmYear.Text);
                    DateTime dtStart = new DateTime(nBgmYear - 544, 10, 1);
                    DateTime dtEnd = new DateTime(nBgmYear - 543, 9, 30);

                    // ล้างรายได้ ค่าใช้จ่าย
                    IncomeVsOutcome("1", dtStart, dtEnd, nBgmYear);
                    IncomeVsOutcome("11", dtStart, dtEnd, nBgmYear);

                    // ยอดยกมา
                    //Transfer("1", dtStart, dtEnd);
                    //Transfer("11", dtStart, dtEnd);

                    grd1.DataSource = ((List<M_ACM_GENERAL_Ledger>)ViewState["modelMains"]);
                    grd1.DataBind();
                }
                else
                {
                    lblError1.Text = "กรุณากรอกปีงบประมาณให้ถูกต้อง";
                    return;
                }

                lblError1.Text = "";
            }
            catch (Exception ex)
            {
                lblError1.Text = ex.Message;
            }
        }

        private void IncomeVsOutcome(string strBgmSourceSeq, DateTime dtStart, DateTime dtEnd, int nBgmYear)
        {
            //int nBgmYear = Convert.ToInt32(txtBgmYear.Text);
            double dInconeVsOutcome = gl.GetIncomeVsOutcome(strBgmSourceSeq, dtStart, dtEnd, nBgmYear);
            List<M_ACM_GENERAL_Ledger> TransferList = gl.GetDataToTransferAccount4and5(nBgmYear.ToString(), strBgmSourceSeq);
            var modelMains = (List<M_ACM_GENERAL_Ledger>)ViewState["modelMains"];
            var modelSubs = (List<M_ACM_GENERAL_Ledger>)ViewState["modelSubs"];

            M_ACM_GENERAL_Ledger modelMain = new M_ACM_GENERAL_Ledger();
            modelMain.tran_seq = Convert.ToInt32(strBgmSourceSeq);
            modelMain.tran_type = "C";
            modelMain.fiscal_period = (nBgmYear - 543).ToString() + "/" + "10";
            modelMain.tran_code = gl.GetNextTranCode(strBgmSourceSeq, (nBgmYear).ToString(), "C");
            modelMain.tran_date = dtEnd;
            modelMain.bgm_year = nBgmYear;
            modelMain.work_area_seq = null;
            modelMain.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            modelMain.bgm_source_name = strBgmSourceSeq == "1" ? "เงินงบประมาณ" : "เงินรายได้";
            modelMain.tran_name = "ปิดงวดบัญชีประจำปี " + txtBgmYear.Text;
            modelMain.record_status = "A";
            modelMain.created_by = Convert.ToInt32(Session["EmpSeq"]);
            modelMain.created_when = DateTime.Now;

            for (int i = 0; i < TransferList.Count; i++)
            {
                TransferList[i].dr_or_cr = TransferList[i].dr_or_cr == "Dr" ? "Cr" : "Dr";
            }

            modelMains.Add(modelMain);
            modelSubs.AddRange(TransferList);
            M_ACM_MAS_BaseAccount modelBase = baseAccount.GetList();
            M_ACM_MAS_Account accountInfo = account.GetInfo_ByAccountSeq_Version(modelBase.close_capital_account_seq, null);

            if (dInconeVsOutcome != 0)
            {
                modelSubs.Add(new M_ACM_GENERAL_Ledger()
                {
                    tran_seq = Convert.ToInt32(strBgmSourceSeq),
                    account_seq = modelBase.close_capital_account_seq,
                    account_code = accountInfo.account_code,
                    account_name = accountInfo.account_name,
                    debit_amount = dInconeVsOutcome < 0 ? -dInconeVsOutcome : 0,
                    credit_amount = dInconeVsOutcome > 0 ? dInconeVsOutcome : 0,
                    dr_or_cr = dInconeVsOutcome < 0 ? "Dr" : "Cr",
                    amount = dInconeVsOutcome,
                    record_status = "W"
                });
            }
            /*
            M_ACM_GENERAL_Ledger modelSub1 = new M_ACM_GENERAL_Ledger();
            M_ACM_GENERAL_Ledger modelSub2 = new M_ACM_GENERAL_Ledger();
            M_ACM_MAS_BaseAccount modelBase = baseAccount.GetList();
            int nDrAccountSeq = 0;
            int nCrAccountSeq = 0;

            if (dInconeVsOutcome > 0)
            {
                nDrAccountSeq = modelBase.close_income_account_seq ?? 0;
                nCrAccountSeq = modelBase.close_capital_account_seq ?? 0;
            }
            else if (dInconeVsOutcome < 0)
            {
                nDrAccountSeq = modelBase.close_capital_account_seq ?? 0;
                nCrAccountSeq = modelBase.close_outcome_account_seq ?? 0;
            }

            var modelAccount = account.GetInfo_ByAccountSeq_Version(nDrAccountSeq, null);

            modelSub1.tran_seq = Convert.ToInt32(strBgmSourceSeq);
            modelSub1.account_seq = nDrAccountSeq;
            modelSub1.account_code = modelAccount.account_code;
            modelSub1.account_name = modelAccount.account_name;
            modelSub1.dr_or_cr = "Dr";
            modelSub1.amount = dInconeVsOutcome;
            modelSub1.debit_amount = dInconeVsOutcome;
            modelSub1.credit_amount = 0;
            modelSub1.record_status = "W";
            modelSub1.created_by = Convert.ToInt32(Session["EmpSeq"]);
            modelSub1.created_when = DateTime.Now;

            modelSubs.Add(modelSub1);

            modelAccount = account.GetInfo_ByAccountSeq_Version(nCrAccountSeq, null);

            modelSub2.tran_seq = Convert.ToInt32(strBgmSourceSeq);
            modelSub2.account_seq = nCrAccountSeq;
            modelSub2.account_code = modelAccount.account_code;
            modelSub2.account_name = modelAccount.account_name;
            modelSub2.dr_or_cr = "Cr";
            modelSub2.amount = dInconeVsOutcome;
            modelSub2.debit_amount = 0;
            modelSub2.credit_amount = dInconeVsOutcome;
            modelSub2.record_status = "W";
            modelSub2.created_by = Convert.ToInt32(Session["EmpSeq"]);
            modelSub2.created_when = DateTime.Now;

            modelSubs.Add(modelSub2);
            */

            ViewState["modelMains"] = modelMains;
            ViewState["modelSubs"] = modelSubs;
        }

        private void Transfer(string strBgmSourceSeq, DateTime dtStart, DateTime dtEnd)
        {
            int nBgmYear = Convert.ToInt32(txtBgmYear.Text);
            DataTable dtb = gl.ReportIncomeStatments(strBgmSourceSeq, dtStart, dtEnd, "'1', '2', '3'", null, true);
            var modelMains = (List<M_ACM_GENERAL_Ledger>)ViewState["modelMains2"];
            var modelSubs = (List<M_ACM_GENERAL_Ledger>)ViewState["modelSubs2"];

            if (dtb.Rows.Count > 0)
            {
                M_ACM_GENERAL_Ledger modelMain = new M_ACM_GENERAL_Ledger();
                modelMain.tran_seq = Convert.ToInt32("555" + strBgmSourceSeq);
                modelMain.tran_type = "G";
                modelMain.fiscal_period = (nBgmYear + 1 - 543).ToString() + "/" + "10";
                modelMain.tran_code = gl.GetNextTranCode("1", (nBgmYear + 1).ToString(), "G");
                modelMain.tran_date = dtEnd.AddDays(1);
                modelMain.bgm_year = nBgmYear;
                modelMain.work_area_seq = null;
                modelMain.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
                modelMain.tran_name = "ยดยกมาจากงวดบัญชีประจำปี " + txtBgmYear.Text;
                modelMain.record_status = "W";
                modelMain.created_by = Convert.ToInt32(Session["EmpSeq"]);
                modelMain.created_when = DateTime.Now;

                modelMains.Add(modelMain);

                foreach (DataRow dr in dtb.Rows)
                {
                    M_ACM_GENERAL_Ledger modelSub = new M_ACM_GENERAL_Ledger();
                    string strDrOrCr = "";
                    double dAmount = main.ConvertNullDouble(dr["amount"]) ?? 0;
                    double dDrAmount = 0;//main.ConvertNullDouble(dr["amount"]) ?? 0;
                    double dCrAmount = 0;// main.ConvertNullDouble(dr["amount"]) ?? 0;

                    switch (dr["account_group"].ToString())
                    {
                        case "1":
                        case "3":
                            strDrOrCr = dAmount >= 0 ? "Dr" : "Cr";
                            dDrAmount = dAmount >= 0 ? dAmount : 0;
                            dCrAmount = dAmount >= 0 ? 0 : -dAmount;
                            break;
                        case "2":
                            strDrOrCr = dAmount >= 0 ? "Cr" : "Dr";
                            dDrAmount = dAmount <= 0 ? -dAmount : 0;
                            dCrAmount = dAmount <= 0 ? 0 : dAmount;
                            break;
                    }

                    modelSub.tran_seq = Convert.ToInt32("555" + strBgmSourceSeq);
                    modelSub.account_seq = main.ConvertNullInt(dr["account_seq"]);
                    modelSub.account_code = dr["account_code"].ToString();
                    modelSub.account_name = dr["account_name"].ToString();
                    modelSub.dr_or_cr = dDrAmount > 0 ? "Dr" : "Cr";
                    modelSub.amount = dDrAmount > 0 ? dDrAmount : dCrAmount;
                    modelSub.debit_amount = dDrAmount;
                    modelSub.credit_amount = dCrAmount;
                    modelSub.record_status = "W";
                    modelSub.created_by = Convert.ToInt32(Session["EmpSeq"]);
                    modelSub.created_when = DateTime.Now;

                    modelSubs.Add(modelSub);
                }
            }

            ViewState["modelMains2"] = modelMains;
            ViewState["modelSubs2"] = modelSubs;
        }

        protected void grd2_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
        {
            GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem;
            int nTranSeq = main.ConvertNullInt(main.WebString(dataItem["tran_seq"].Text)) ?? 0;
            e.DetailTableView.DataSource = ((List<M_ACM_GENERAL_Ledger>)ViewState["modelSubs2"]).Where(m => m.tran_seq == nTranSeq).ToList();
        }

        protected void cmdSave2_Click(object sender, EventArgs e)
        {
            int nEmpSeq = Convert.ToInt32(Session["EmpSeq"]);

            try
            {
                var modelMains = (List<M_ACM_GENERAL_Ledger>)ViewState["modelMains2"];
                var modelSubs = (List<M_ACM_GENERAL_Ledger>)ViewState["modelSubs2"];

                //INSERT Transaction_group case have new group
                foreach (M_ACM_GENERAL_Ledger modelMain in (List<M_ACM_GENERAL_Ledger>)modelMains)
                {
                    int nOldTranSeq = modelMain.tran_seq;
                    modelMain.created_when = DateTime.Now;

                    string strTranSeq = gl.Insert_Transaction(modelMain, true);

                    if (string.IsNullOrEmpty(strTranSeq))
                    {
                        return;
                    }

                    foreach (M_ACM_GENERAL_Ledger modelSub in modelSubs.Where(m => m.tran_seq == nOldTranSeq).ToList())
                    {
                        modelSub.tran_seq = Convert.ToInt32(strTranSeq);
                        modelSub.created_when = DateTime.Now;

                        gl.Insert_DB_CR(modelSub);
                    }
                }

                main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

            }
        }
    }
}
